<script setup>
import { ref, onMounted, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import CrudTable from '../components/CrudTable.vue'
import FormDialog from '../components/FormDialog.vue'
import { listRole, getRole, addRole, updateRole, delRole } from '../api/role'

// 表格数据
const tableData = ref([])
// 表格加载状态
const loading = ref(false)
// 对话框可见性
const dialogVisible = ref(false)
// 是否为编辑模式
const isEdit = ref(false)
// 表单加载状态
const formLoading = ref(false)

// 权限选项
const permissionOptions = [
  { label: '用户管理', value: 'user' },
  { label: '科室管理', value: 'department' },
  { label: '角色管理', value: 'role' },
  { label: '排班管理', value: 'schedule' },
  { label: '请假管理', value: 'leave' },
  { label: '调班管理', value: 'shift' }
]

// 表单数据
const formData = reactive({
  id: null,
  roleName: '',
  permissions: ''
})

// 选中的权限列表
const selectedPermissions = ref([])

// 监听权限变化，更新表单数据
const updatePermissions = () => {
  formData.permissions = selectedPermissions.value.join(',')
}

// 从字符串解析权限到数组
const parsePermissions = (permissionsStr) => {
  if (!permissionsStr) return []
  return permissionsStr.split(',')
}

// 表单校验规则
const rules = {
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  permissions: [
    { required: true, message: '请选择权限', trigger: 'change' }
  ]
}

// 表格列配置
const columns = [
  { prop: 'id', label: 'ID', width: '80' },
  { prop: 'roleName', label: '角色名称', width: '150' },
  { prop: 'permissions', label: '权限描述', formatter: (row) => {
    const perms = parsePermissions(row.permissions)
    return perms.map(perm => {
      const option = permissionOptions.find(opt => opt.value === perm)
      return option ? option.label : perm
    }).join(', ')
  }},
  { prop: 'createTime', label: '创建时间', width: '180' }
]

// 获取表格数据
const fetchTableData = async () => {
  loading.value = true
  try {
    tableData.value = await listRole()
  } catch (error) {
    console.error('获取角色列表失败:', error)
    ElMessage.error('获取角色列表失败')
  } finally {
    loading.value = false
  }
}

// 重置表单数据
const resetFormData = () => {
  Object.assign(formData, {
    id: null,
    roleName: '',
    permissions: ''
  })
  selectedPermissions.value = []
}

// 处理新增
const handleAdd = () => {
  resetFormData()
  isEdit.value = false
  dialogVisible.value = true
}

// 处理编辑
const handleEdit = async (row) => {
  try {
    const roleDetail = await getRole(row.id)
    Object.assign(formData, roleDetail)
    selectedPermissions.value = parsePermissions(roleDetail.permissions)
    isEdit.value = true
    dialogVisible.value = true
  } catch (error) {
    console.error('获取角色详情失败:', error)
    ElMessage.error('获取角色详情失败')
  }
}

// 处理删除
const handleDelete = async (row) => {
  try {
    await delRole(row.id)
    ElMessage.success('删除成功')
    fetchTableData()
  } catch (error) {
    console.error('删除角色失败:', error)
    ElMessage.error('删除角色失败')
  }
}

// 处理表单提交
const handleSubmit = async () => {
  // 先更新权限字符串
  updatePermissions()
  
  formLoading.value = true
  try {
    if (isEdit.value) {
      await updateRole(formData)
      ElMessage.success('更新成功')
    } else {
      await addRole(formData)
      ElMessage.success('创建成功')
    }
    dialogVisible.value = false
    fetchTableData()
  } catch (error) {
    console.error('保存角色失败:', error)
    ElMessage.error('保存角色失败')
  } finally {
    formLoading.value = false
  }
}

// 页面加载时获取数据
onMounted(() => {
  fetchTableData()
})
</script>

<template>
  <div class="role-container">
    <crud-table
      :data="tableData"
      :columns="columns"
      :loading="loading"
      title="角色权限管理"
      @add="handleAdd"
      @edit="handleEdit"
      @delete="handleDelete"
      @refresh="fetchTableData"
    >
      <!-- 表单对话框 -->
      <form-dialog
        v-model:visible="dialogVisible"
        :form-data="formData"
        :rules="rules"
        :is-edit="isEdit"
        :loading="formLoading"
        title="角色"
        @submit="handleSubmit"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="formData.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        
        <el-form-item label="权限设置" prop="permissions">
          <el-checkbox-group v-model="selectedPermissions" @change="updatePermissions">
            <el-checkbox
              v-for="option in permissionOptions"
              :key="option.value"
              :label="option.value"
            >
              {{ option.label }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </form-dialog>
    </crud-table>
  </div>
</template>

<style scoped>
.role-container {
  padding: 20px;
}
</style> 